// pages/store/purchase/setmeal/setmeal.js
import {
  api,
  util
} from '../../../../js/util';
import {comments} from "../../../../js/modules/mall.js";
import authorize from '../../../../js/modules/authorize';
import BasePage from '../../../../js/common/base-page'
import { router} from '../../../../js/router';
import {
  cart
} from "../../../../js/modules/order.js"
import { setStorageSync } from '../../../../js/compatible';

var app = getApp();
BasePage({
  pageKey: "",
  /**
   * 页面的初始数据
   */
  data: {
    navList: [],
    activeIndex: 0,
    scrollLeft: 0,
    packageList: [], //套餐列表
    packageAllList:{},
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    selectNum:0,//勾选套餐
    selectQuantity:0,//套餐数量
    selectedGoods: [], // 已选商品数组
    orginalPrice: 0, // 原价 
    currentPrice: 0, // 现价
    iptNum: 0, //输入num
    isIphoneX: app.globalData.isIphoneX,
    allChecked:false,//全选
    mainColor:'',//主题色
    Currency:'',//货币符号
    CartName:'',//购物车名称
    CartCount:0 //购物车数量
  },
  activeTab: function (e) {
    var index = e.currentTarget.dataset.index;
    var ids = e.currentTarget.dataset.id;
    this.setData({
      activeIndex: index,
      scrollLeft: (index - 2) * 200,
      orginalPrice: 0,
      currentPrice: 0,
      selectedGoods: []
    })
    this.packageDetail(ids);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(JSON.parse(options.id));
    this.setData({
      navList: JSON.parse(options.id)
    })
    var ids = '';

    if (this.data.navList.length > 0) {
      ids = JSON.parse(options.id)[0];
    } else {
      ids = options.id;
    }
    this.pageKey = 'setmeal';
    this.packageDetail(ids);
  },
  /**统计购物车数量 */
  getCartCount() {
    let that = this;
    cart.get_cart_count(function(res) {
      that.setData({
        CartCount: res.Content
      });
    });
  },
  packageDetail: function (id) {
    var that = this;
    var data = {
      PackedSaleId: id
    };
    comments.getPackageDetail(data, function (content) {
      // console.log(content,'=======套餐明细');
      let datas = content.Content;
      let data = datas[0] || {};
      let productList = [];
      for (let i = 0; i < (data.ProductList || []).length; i++) {
        let item = data.ProductList[i];
        if (data.Mode == 1) {
          for (let j = 0; j < (item.GoodsList || []).length; j++) {
            let goods = item.GoodsList[j];
            if (data.Type == 1) {
              goods.checked = true;
            } else {
              goods.checked = productList.length < 2;
            }
            goods.ProductName = item.ProductName;
            goods.DefaultPic = goods.DefaultPic?goods.DefaultPic:item.DefaultPic;
            goods.ModelSpec = item.ModelSpec;
            goods.Manufacturer = item.Manufacturer;
            goods.ShowPrice = item.ShowPrice;
            productList.push(goods);
          }
        } else {
          if (data.Type == 1) {
            item.checked = true;
          } else {
            item.checked = productList.length < 2;
          }
          if (item.GoodsList != undefined && item.GoodsList.length > 0) {
            let firstGoods = item.GoodsList[0];
            item.SpeceIndex = 0;
            item.GoodsId = firstGoods.GoodsId;
            item.SpeceValue = firstGoods.SpecValue;
            item.Quantity = firstGoods.Quantity;
            item.Unit = firstGoods.Unit;
            item.Translated = firstGoods.Translated;
            item.SalesPrice = firstGoods.SalesPrice;
            item.PackedSalePrice = firstGoods.PackedSalePrice;
          }
          productList.push(item);
        }
      }
      that.setData({
        packageList: productList,
        packageAllList:data || {}
      })
      let pageTitle = '优惠套餐';
      that.pageInfo = {
        pageTitle: pageTitle,
        detailText: pageTitle,
        parameter: `PackedSaleId=${id}`
      };
      // console.log('@@@@@@@@@@', productList,data)
      that.setSelectedGoods()
      that.set_select_all_status(that);
    })

  },
  bindPickerChange(e) {
    // console.log(e)
    // let parentIndex = e.currentTarget.dataset.pindex
    let index = e.currentTarget.dataset.index
    let gIndex = Number(e.detail.value)

    let list = this.data.packageList
    let goodsList = list[index].GoodsList || [];
    let indexGoods = goodsList[gIndex];
    list[index].GoodsId = indexGoods.GoodsId;
    list[index].SpeceIndex = gIndex;
    list[index].SpeceValue = indexGoods.SpecValue;
    list[index].Quantity = indexGoods.Quantity;
    list[index].Unit = indexGoods.Unit;
    list[index].Translated = indexGoods.Translated;
    list[index].SalesPrice = indexGoods.SalesPrice;
    list[index].PackedSalePrice = indexGoods.PackedSalePrice;
    list[index].selectedIndex = gIndex
    // list[parentIndex].ProductList[index].selected = [list[parentIndex].ProductList[index].GoodsList[gIndex]]
    // console.log(list,'-----');
    this.setData({
      packageList: list
    })
    this.setSelectedGoods()
  },
  /**
   * 单选
   */
  toggleSelected(e){
    let that = this;
    let index = e.currentTarget.dataset.index;
    let packageList = that.data.packageList;
    packageList[index].checked = !packageList[index].checked
    that.setData({
      packageList: packageList
    })
    // console.log(that.data.packageList,'=====');
    that.setSelectedGoods()
    that.set_select_all_status(that);
  },
  setSelectedGoods() {
    let packageList = this.data.packageList
    // let list = []
    let currentPrice = 0,orginalPrice = 0,selectNum=0,selectQuantity=0;
    // let orginalPrice = 0
    // 添加数组到选中商品的数组中
    for (let i = 0; i < packageList.length; i++) {
      if (packageList[i].checked) {
        currentPrice += packageList[i].PackedSalePrice * packageList[i].Quantity;
        orginalPrice += packageList[i].SalesPrice * packageList[i].Quantity;
        selectNum += 1;
        selectQuantity += packageList[i].Quantity;
      }
    }
    this.setData({
      // selectedGoods: list,
      orginalPrice: (orginalPrice * (this.data.iptNum || 1)).toFixed(2),
      currentPrice: (currentPrice * (this.data.iptNum || 1)).toFixed(2),
      selectNum:selectNum,
      selectQuantity:selectQuantity
    })
    // console.log('选中的商品信息>>>>', this.data.selectedGoods,this.data.packageList)
  },
  /**
   * 加
   */
  bindAdd: function () {
    this.data.iptNum++;
    var list = this.data.packageAllList
    var num = list.RestrictNum>0?list.RestrictNum:(list.Num > 0 ? list.Num : Number.MAX_SAFE_INTEGER);
    if(num < this.data.iptNum){
      wx.showToast({
        title: "已达到最大数量："+num,
        icon: 'none',
        duration: 2000
      })
      this.data.iptNum = num
    }
    this.setData({
      iptNum: this.data.iptNum
    })
    this.setSelectedGoods()
  },
  /**
   * 输入数量
   */
  bindNum: function (e) {
    var num = e.detail.value.replace(/^(\-)*(\d+)\.(\d{6}).*$/, '$1$2.$3');
    num = num.replace(/[\u4e00-\u9fa5]+/g, "");
    num = num.replace(/[^\d.]/g, "");
    num = num.replace(/^\./g, "");
    num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    if (num < 0) {
      num = 0;
    }
    this.setData({
      iptNum: num
    })
    this.setSelectedGoods()
  },
  /**
   * 减
   */
  bindReduce: function () {
    this.data.iptNum--;
    if (this.data.iptNum < 0) {
      this.data.iptNum = 0;
    }
    this.setData({
      iptNum: this.data.iptNum
    })
    this.setSelectedGoods()
  },
  /**
   * 全选
   */
  onSelectAllEvent:function(e){
    var that = this;
    that.data.allChecked = (that.data.allChecked ? false : true);
    var list = that.data.packageList;
    for (var i = 0; i < list.length; i++) {
      list[i].checked = that.data.allChecked;
    }
    that.setData({
      packageList:list,
      allChecked:that.data.allChecked
    })
    this.setSelectedGoods()
    // console.log(that.data.packageList,'=====');
  },
  /**获得全选状态 */
  set_select_all_status: function(that) {
    var num = 0;
    var list = that.data.packageList;
    list.map(function (seller, i) {
      if (seller.checked != true) num++;
    });
    that.setData({
      allChecked: list.length>0&&num<1
    });
  },
  /**跳转到购物车页面 */
  gotoCart() {
    setStorageSync('tabindex', app.dns.cartNum)
    router.switchTab({
      path: 'cart'
    });
  },
  /**跳转到首页页面 */
  goHome(){
    router.switchTab({
      path: "index"
    });
  },
  /**
   * 加入购物车
   */
  btnJoin: function () {
    if (this.data.selectNum < 2) {
      wx.showToast({
        title: "至少选择2件套餐商品！！！",
        icon: 'none',
        duration: 2000
      })
      return;
    } else if (this.data.iptNum == 0) {
      wx.showToast({
        title: "请确定下单数量！！！",
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var list = this.data.packageList;
    var goodId = [];
    for (var i = 0; i < list.length; i++) {
      if(list[i].checked){
        goodId.push(list[i].GoodsId)
      }
    }
    var packedId = this.data.packageAllList.Id;
    var data = {
      num: this.data.iptNum,
      GoodsIds: goodId,
      PackedId: packedId
    };
    console.log(data,'-----1');
    cart.packedAddCart(data, function (content) {
      util.success("加入成功！");
    })
  },
  /**
   * 立即购买
   */
  buyMultiNow: function (e) {
    // this.selectComponent("#productSpec").onBuyEvent(); 
    if (this.data.selectNum < 2) {
      wx.showToast({
        title: "至少选择2件套餐商品！！！",
        icon: 'none',
        duration: 2000
      })
      return;
    } else if (this.data.iptNum == 0) {
      wx.showToast({
        title: "请确定下单数量！！！",
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var list = this.data.packageList;
    console.log(list,'====list');
    var ary = [];

    for (var i = 0; i < list.length; i++) {
      if(list[i].checked){
        var buyGood = list[i];
        var translated = buyGood.Translated || buyGood.Radix;
        translated = (isNaN(translated) || translated == undefined) ? 1 : translated;
        var num = this.data.iptNum; //当前个数
        ary.push("<Goods><SupplierId>" + app.dns.proprietorId + "</SupplierId><FlagId>2</FlagId><BuyTypeId>0</BuyTypeId><BuyType>Product</BuyType><productid>" + buyGood.ProductId + "</productid><goodsid>" + buyGood.GoodsId + "</goodsid><specvalue><![CDATA[" + (buyGood.SpecValue == "无" ? "" : buyGood.SpecValue) + "]]></specvalue><quantity>" + buyGood.Quantity + "</quantity><DiscountType>5</DiscountType><DiscountId>" + buyGood.PackedSaleId + "</DiscountId><AuxUnit>" + (buyGood.DefaultUnit || buyGood.Unit) + "</AuxUnit><AuxRate>" + translated + "</AuxRate><AuxQty>" + buyGood.Quantity + "</AuxQty><Multiple>" + num + "</Multiple></Goods>");
      }
    }
    // console.log(ary.join(''),'-----list');
    // return;
    var productinfo = ary.join('');
    var info = util.base64_encode(productinfo);
    // console.log(productinfo,'=======',util.base64_encode(productinfo));
    // return;
    var params = {
      path: "orderConfirm",
      params: {
        productinfo: info
      }
    }
    router.navigate(params);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      mainColor:api.titleColor||"#e56b14",
      Currency:api.Currency || '￥',
      CartName:api.CartName || '购物车'
    });
    this.getCartCount();
  },

  /**
   * 跳转商品详情
   */
  toProductDetail (e) {
    let index = e.currentTarget.dataset.index
    let list = this.data.packageList || []
    let item = list[index] || {}
    console.log(item, item.productId);
    router.navigate({
      path: 'packageStore/pages/product/detail/detail',
      params: {
        ProductId: item.ProductId || '',
        id: item.ProductId || '',
      }
    })
  },
  /**
   * 防止点击picker触发跳转
   */
  nothing () {
    return false
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})